package com.example.test622.detail

import android.widget.Toast
import androidx.lifecycle.lifecycleScope
import com.example.common.CommonAdapter
import com.example.common.CommonViewHolder
import com.example.common.mvi.BaseFragment
import com.example.net.Dao.DataBase
import com.example.net.entity.RecommonVideoEntity
import com.example.net.entity.SimpleVideoEntity
import com.example.test622.BR
import com.example.test622.R
import com.example.test622.databinding.FragmentHomeDetailRecommonBinding
import com.example.test622.databinding.RecommonBinding
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext


class HomeDetailRecommonFragment : BaseFragment<FragmentHomeDetailRecommonBinding,RecomonViewModel>() {
	var list: MutableList<RecommonVideoEntity> = mutableListOf()
	val adapter by lazy {
		object :CommonAdapter<RecommonVideoEntity>({R.layout.recommon to BR.video}){
			override fun onBindViewHolder(holder: CommonViewHolder, position: Int) {
				super.onBindViewHolder(holder, position)
				val recommonBinding = holder.binding as RecommonBinding
					val db = DataBase.getDataBase(requireActivity())
					recommonBinding.recommonImg.setOnClickListener{
//						val newVideo = RecommonVideoEntity(list[position].actorlist,list[position].albumgroupid,list[position].albumid,list[position].arealist,list[position].avatar_url,
//							list[position].cover_height,list[position].cover_largeurllist,list[position].cover_mediumurllist,list[position].cover_thumburllist,list[position].cover_uri,
//							list[position].cover_url,list[position].cover_urllist,list[position].cover_width,list[position].ctime,list[position].description,list[position].duration,
//							list[position].favoritecount,list[position].id, list[position].intro,list[position].languageinfo,list[position].name,list[position].shareurl,list[position].subtitle,
//							list[position].taglist,list[position].title,list[position].toutiaolvideotext,list[position].userid,list[position].verifycode,list[position].videomainimag,list[position].videopath,
//							list[position].videotypeid,list[position].year)
						val get = list[position]
						lifecycleScope.launch {
							withContext(Dispatchers.IO){
								db.videoDao().insertVideo(get)
							}
							withContext(Dispatchers.Main){
								Toast.makeText(
									requireContext(),
									"添加数据库成功",
									Toast.LENGTH_SHORT
								).show()
							}
						}
					}
				
			}
		}
	}
	override fun initView() {
		binding.recDetail.adapter = adapter
	}
	
	override fun initData() {
		viewModel.state.observe(this){
			when(it){
				is RecommonState.RecommonSuccess->{
					list.addAll(it.recommon.data)
					adapter+=list
				}
				is RecommonState.RecommonFail->{
					Toast.makeText(requireContext(), "${it.error}", Toast.LENGTH_SHORT).show()
				}
			}
		}
		viewModel.intent.trySend(RecommonIntent.getRecommonVideo(1,10))
	}
	
}